import { ipcMain } from 'electron'
import * as cheerio from 'cheerio'
import ejs from 'ejs'
import fs from 'fs'
import pinyin from 'js-pinyin'
import prettier from 'prettier'

export const setupDomToFormHandlers = () => {
  ipcMain.handle('dom-to-form', (_event, richText: any) => {
    return new Promise(async (resolve) => {
      const formConfig = getFormConfig(richText)
      console.log(formConfig)
      const formRes = await renderForm(formConfig)
      const rulesRes = await renderRules(formConfig)
      const res = {
        form: formRes,
        rules: rulesRes
      }
      resolve(res)
    })
  })
}

const renderForm = (formConfig: any) => {
  return new Promise((resolve, reject) => {
    fs.readFile('./src/main/handlers/domToForm/form.ejs', 'utf8', (err, template) => {
      if (err) {
        reject(err)
        console.error('Error reading template:', err)
        return
      }

      // 渲染模板，并传递变量
      const renderedTemplate = ejs.render(template, {
        formConfig
      })

      const formattedTemplate = prettier.format(renderedTemplate, {
        parser: 'vue',
        printWidth: 120,
        tabWidth: 4,
        useTabs: true
      })

      resolve(formattedTemplate)
    })
  })
}

const renderRules = (formConfig: any) => {
  return new Promise((resolve, reject) => {
    fs.readFile('./src/main/handlers/domToForm/rules.ejs', 'utf8', (err, template) => {
      if (err) {
        reject(err)
        console.error('Error reading template:', err)
        return
      }

      // 渲染模板，并传递变量
      const renderedTemplate = ejs.render(template, {
        formConfig
      })

      const formattedTemplate = prettier.format(renderedTemplate, {
        parser: 'typescript',
        printWidth: 120,
        tabWidth: 4,
        useTabs: true
      })

      resolve(formattedTemplate)
    })
  })
}

const getFormConfig = (cleanHtml) => {
  const $ = cheerio.load(cleanHtml)
  const formConfig: any = {
    fields: []
  }
  // 遍历.el-form下所有label
  $('.el-form .el-form-item__label').each(function () {
    const label = $(this).text().trim()
    if (label && label !== '请选择') {
      // 查找label最近的.el-form-item下.el-form-item__content的类型
      let type = 'any'
      const formItem = $(this).closest('.el-form-item')
      const content = formItem.find('.el-form-item__content')
      // 查找el-col-栅格数
      let span = 24
      let parent = formItem.parent()
      while (parent && parent.length) {
        const className = parent.attr('class') || ''
        const match = className.match(/el-col-(\d+)/)
        if (match) {
          span = parseInt(match[1], 10)
          break
        }
        parent = parent.parent()
      }
      // 优先判断是否有多个.el-date-editor
      const firstChild = content.children().first()
      // 检查内容区所有子元素中是否包含.ql-editor
      if (content.find('.ql-editor').length > 0) {
        type = 'editor'
      } else {
        if (firstChild.hasClass('el-date-editor')) {
          type = 'date'
        } else if (firstChild.hasClass('upload')) {
          type = 'photo'
        } else if (firstChild.hasClass('avatar-uploader')) {
          type = 'photo'
        } else if (firstChild.hasClass('el-input')) {
          type = 'text'
        } else if (firstChild.hasClass('el-textarea')) {
          type = 'textarea'
        } else if (firstChild.hasClass('el-input-number')) {
          type = 'number'
        } else if (firstChild.hasClass('el-range-editor')) {
          type = 'dateRange'
        } else if (firstChild.hasClass('el-select')) {
          type = 'select'
        } else if (firstChild.hasClass('el-radio-group')) {
          type = 'radio'
        } else if (firstChild.hasClass('el-checkbox-group') || firstChild.hasClass('el-checkbox')) {
          type = 'checkbox'
        } else if (firstChild.hasClass('el-cascader')) {
          type = 'cascader'
        }
      }
      formConfig.fields.push({
        label,
        type,
        required: formItem.hasClass('is-required'),
        span
      })
    }
  })
  formConfig.fields.forEach((item) => {
    item.name = getPinYin(item.label)
  })
  console.log(formConfig)
  return formConfig
}

const getPinYin = (text: string) => {
  text = text.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '')
  const str = pinyin.getCamelChars(text).toLowerCase()
  return `_temp_${str}`
}
